package com.fary.chapter03_ext_callable;

import lombok.SneakyThrows;

public class FaryFutureTask1<V> implements Runnable {
    private final FaryCallable<V> faryCallable;
    private Thread cuThread;
    private V result;
    private final Object lock = new Object();

    public FaryFutureTask1(FaryCallable<V> faryCallable) {
        this.faryCallable = faryCallable;
    }

    @SneakyThrows
    @Override
    public void run() {
        // 获取到faryCallable 执行返回结果
        result = faryCallable.call();
        // 如果 call方法执行完毕 则唤醒当前阻塞的线程
        if (cuThread != null)
            synchronized (lock) {
                lock.notify();
            }
    }

    /**
     * 调用get方法 当前线程就会阻塞。
     */
    public V get() {
        cuThread = Thread.currentThread();
        synchronized (lock) {
            try {
                // 当前线程释放锁 变为阻塞状态
                lock.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}